/**
 * 
 */
package systole.processor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import systole.domain.signals.Segment;
import systole.domain.signals.Signal;
import systole.processor.correlation.Correlation;
import systole.processor.correlation.CorrelationByResult;
import systole.processor.correlation.CorrelationBySegment;
import systole.processor.correlation.CorrelationKind;
import systole.processor.correlation.CorrelationResult;

/**
 * @author juan
 *
 */
public class Qualifier {

    private Correlation correlation;
    private BigDecimal minCorrelation;
    private int maxAmount;
    private List<CorrelationResult> results;

    /**
     *
     * @param segment
     * @param minCorrelation
     * @param maxAmount
     * @param kind
     */
    public Qualifier(Segment segment, BigDecimal minCorrelation, int maxAmount, CorrelationKind kind) {
        this.minCorrelation = minCorrelation;
        this.maxAmount = maxAmount;

        switch (kind) {
            case RESULTADO:
                this.correlation = new CorrelationByResult(segment);
                break;
            case SEGMENTO:
                this.correlation = new CorrelationBySegment(segment);
                break;
        }
    }

    /**
     *
     * @param allSegments
     * @return correlation result list
     */
    public List<CorrelationResult> qualify(Signal allSegments) {
        this.results = new ArrayList<CorrelationResult>();
        Iterator<Segment> itSegments = allSegments.getSegments().iterator();
        int pos = 0;
        CorrelationResult result;
        while (itSegments.hasNext()) {
            result = new CorrelationResult(pos, this.correlation.correlate(itSegments.next()));
            pos++;
            this.results.add(result);
        }
        Collections.sort(this.results);
        Collections.reverse(this.results);

        List<CorrelationResult> segments = new ArrayList<CorrelationResult>();
        int i = 0;
        while ((i < this.results.size()) && (this.minCorrelation.compareTo(this.results.get(i).getCorrelation()) <= 0)
                && (this.maxAmount > segments.size())) {
            segments.add(this.results.get(i));
            i++;
        }

        return segments;
    }
}
